#include "threadLock.h"


/**
 * @brief: 线程锁初始化
 * @function: 初始化线程锁
 * @param: threadLock 线程锁结构体
 * @return: 无
 * @note: 无
 */
int threadLockInit(T_THREAD_LOCK* threadLock) {
	if (NULL == threadLock) {
		return -1;
	}
	int ret = pthread_mutexattr_init(&threadLock->m_mutexattr);
	ret |= pthread_mutexattr_settype(&threadLock->m_mutexattr, PTHREAD_MUTEX_RECURSIVE);
	ret |= pthread_mutex_init(&threadLock->m_mutex, &threadLock->m_mutexattr);
	ret |= pthread_cond_init(&threadLock->m_cond, NULL);
	return (0 == ret) ? 0 : -1;
}
/**
 * @brief: 线程锁销毁
 * @function: 销毁线程锁
 * @param: threadLock 线程锁结构体
 * @return: 无
 * @note: 无
 */
int threadLockDestroy(T_THREAD_LOCK* threadLock) {
	if(NULL == threadLock){
		return -1;
	}
	int ret = pthread_mutexattr_destroy(&threadLock->m_mutexattr);
	ret |= pthread_mutex_destroy(&threadLock->m_mutex);
	ret |= pthread_cond_destroy(&threadLock->m_cond);
	return (0 == ret) ? 0 : -1;
}
/**
 * @brief: 线程锁获取锁
 * @function: 获取线程锁
 * @param: threadLock 线程锁结构体
 * @return: 无
 * @note: 无
 */
int threadLockLock(T_THREAD_LOCK* threadLock){
	if(NULL == threadLock){
		return -1;
	}
	return pthread_mutex_lock(&threadLock->m_mutex);
}

int threadLockUnlock(T_THREAD_LOCK* threadLock){
	if(NULL == threadLock){
		return -1;
	}
	return pthread_mutex_unlock(&threadLock->m_mutex);
}

/**
 * @Description: 线程等待条件变量信号
 * @return: 无
 */
int threadLockWait(T_THREAD_LOCK* threadLock){
	if(NULL == threadLock){
		return -1;
	}
	return pthread_cond_wait(&threadLock->m_cond, &threadLock->m_mutex);
}

/**
 * @Description: 线程等待超时条件变量信号
 * @return: 无
 */
int threadLockTimeWait(T_THREAD_LOCK* threadLock, int ms){ 
	struct timeval now;
	struct timespec timeout;

	gettimeofday(&now, NULL);
	timeout.tv_sec = now.tv_sec + ms/1000;
	timeout.tv_nsec = (now.tv_usec + ms%1000 * 1000) * 1000;

	return pthread_cond_timedwait(&threadLock->m_cond, &threadLock->m_mutex, &timeout); 
}

/**
 * @Description: 线程触发条件变量
 * @return: 无
 */
extern int threadLockSignal(T_THREAD_LOCK* threadLock){
	if(NULL == threadLock){
		return -1;
	}
	return pthread_cond_signal(&threadLock->m_cond);
}